package job_center

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"git.mycaigou.com/gfyx/common/authorize"
	"git.mycaigou.com/gfyx/common/cache"
	dto "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/job_center"
	jobCenterRepo "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/repository/job_center"
	pb "git.mycaigou.com/gfyx/micro-gfyx-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/job_center"
	"time"
)

type jobCenterService struct {
	jobCenterRepo jobCenterRepo.JobCenterRepositoryIface
}

func NewJobCenterService(
	jobCenterRepo jobCenterRepo.JobCenterRepositoryIface,
) JobCenterServiceIface {
	return &jobCenterService{
		jobCenterRepo: jobCenterRepo,
	}
}

func (s *jobCenterService) GetMyJobList(ctx context.Context, request *dto.MyListRequest) (*dto.MyListResponse, error) {
	resp, err := s.jobCenterRepo.GetMyJobList(ctx, &pb.GetMyJobListRequest{
		Status:    request.Status,
		Page:      request.Page,
		PageSize:  request.PageSize,
		BeginTime: time.Now().AddDate(-1, 0, 0).Format("2006-01-02 15:04:05"),
	})
	if err != nil {
		return nil, err
	}
	if resp == nil {
		return nil, errors.New("获取任务列表数据失败")
	}
	result := &dto.MyListResponse{
		Total: resp.Total,
		List:  make([]*dto.JobItem, 0),
	}
	if len(resp.List) == 0 {
		return result, nil
	}

	for _, jobPb := range resp.List {
		jobDto := &dto.JobItem{
			Id:            jobPb.Id,
			Title:         jobPb.Title,
			Type:          jobPb.Type,
			Status:        jobPb.Status,
			FinishStatus:  jobPb.FinishStatus,
			FinishedTime:  jobPb.FinishedTime,
			Result:        jobPb.Result,
			CreatedTime:   jobPb.CreatedTime,
			ResultFileUrl: jobPb.ResultFileUrl,
		}
		result.List = append(result.List, jobDto)
	}
	return result, nil
}

func (s *jobCenterService) RerunJob(ctx context.Context, request *dto.RerunJobRequest) error {
	resp, err := s.jobCenterRepo.RerunJob(ctx, &pb.RerunJobRequest{
		Id: request.Id,
	})
	if err != nil {
		return err
	}
	if resp == nil || resp.IsSuccess == false {
		return errors.New("重跑任务失败")
	}

	return nil
}

func (s *jobCenterService) FinishedJobNotice(ctx context.Context) (*dto.FinishedJobNoticeResponse, error) {
	resp := dto.FinishedJobNoticeResponse{
		List: make([]*dto.JobItem, 0),
	}

	tenantCache, _ := cache.TenantRedis()
	//每次最多取5条
	for i := 0; i < 5; i++ {
		result, err := tenantCache.LPop(ctx, fmt.Sprintf("finished-notice:%d", authorize.GetUserId(ctx)))
		if err != nil {
			return nil, err
		}
		if result == "" {
			break
		}
		var jobPbs []pb.JobItem
		err = json.Unmarshal([]byte(result), &jobPbs)
		if err != nil {
			continue
		}
		if len(jobPbs) > 0 {
			for _, jobPb := range jobPbs {
				resp.List = append(resp.List, &dto.JobItem{
					Id:           jobPb.Id,
					Title:        jobPb.Title,
					Type:         jobPb.Type,
					Status:       jobPb.Status,
					FinishStatus: jobPb.FinishStatus,
					FinishedTime: jobPb.FinishedTime,
					Result:       jobPb.Result,
					CreatedTime:  jobPb.CreatedTime,
				})
			}
		}

	}

	return &resp, nil
}
